package com.community.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.dto.ProductSales;
import com.community.dto.SaleDto;
import com.community.pojo.Employee;
import com.community.pojo.EmployeeQuery;
import com.community.pojo.EmployeeRole;
import com.community.pojo.Role;
import com.community.service.IEmployeeRoleService;
import com.community.service.IEmployeeService;

import com.community.service.IProductService;
import com.community.service.IRoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 员工表 前端控制器
 * </p>
 *
 * @author TangHaoSong Fly ChenJie HeYuHang
 * @since 2024-05-15
 */
@CrossOrigin
@RestController
@RequestMapping("/community/employee")
public class EmployeeController {

    @Resource
    private IEmployeeService employeeService;

    @Resource
    private IRoleService roleService;


    @Autowired
    private IEmployeeRoleService employeeRoleService;

    @Resource
    private IProductService productService;

    /**
     * 获取每个月的销售额
     */
    @RequestMapping("/productSale")
    @ResponseBody
    public Integer[] productSale() {
        List<SaleDto> saleDtoList = productService.productSale();

        // 创建长度为12的数组，用于存储销售额数据，初始值为0
        Integer[] salesData = new Integer[12];

        for (SaleDto saleDto : saleDtoList) {
            // 获取当前月的销售额
            int monthSales = saleDto.getMonthlySales();

            // 获取当前月份的数字表示，比如一月对应索引 0
            int monthIndex = getMonthIndex(saleDto.getSalesMonth());

            // 将销售额存入对应月份的索引位置
            salesData[monthIndex] = monthSales;
        }

        return salesData;
    }

    /**
     * 根据月份名称返回月份的索引，比如一月对应索引 0
     * @param month
     * @return
     */
    private int getMonthIndex(String month) {
        switch (month) {
            case "1": return 0;
            case "2": return 1;
            case "3": return 2;
            case "4": return 3;
            case "5": return 4;
            case "6": return 5;
            case "7": return 6;
            case "8": return 7;
            case "9": return 8;
            case "10": return 9;
            case "11": return 10;
            case "12": return 11;
            // 如果出现无效的月份
            default: return -1;
        }
    }

    /**
     * 文件存储根目录，可以配置到配置文件中
     */
    private static final String UPLOAD_DIR = "D:/学习/硅谷/S3/2.黄老师课程/3.Git/项目社团区购/Fly-Test/shopping02/src/assets/img/";

    /**
     * 处理add上传图片
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadImg")
    public String uploadImg(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "error";
        }

        File uploadDirectory = new File(UPLOAD_DIR);
        if (!uploadDirectory.exists()) {
            uploadDirectory.mkdirs();
        }

        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 将时间戳添加到文件名中
        String filename = UUID.randomUUID() + "_" + System.currentTimeMillis() + suffix;

        try {
            file.transferTo(new File(uploadDirectory, filename));

            // 返回经过处理后的文件访问路径
            String fileUrl = "http://localhost:10102/" + filename;
            return fileUrl;
        } catch (IOException e) {
            e.printStackTrace(); // 记录异常信息
            return "error";
        }
    }

    @RequestMapping("/Login")
    public Object login(@RequestBody Employee employee) {
        Employee employee1 = employeeService.getEmployeeByUsername(employee.getUsername());
        if (employee1 != null && employee1.getPassword().equals(employee.getPassword())) {
            // 登录成功
            return employee1;
        } else {
            // 登录失败
            return null;
        }
    }

    @RequestMapping("/getEmployees/{currentPage}/{pageSize}")
    public PageInfo<Employee> getEmployees(@PathVariable int currentPage,
                                           @PathVariable int pageSize,
                                           @RequestBody EmployeeQuery query) {
        // 创建 QueryWrapper 对象
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();

        // 设置查询条件
        Employee employee = query.getEmployee();
        if (StringUtils.hasText(employee.getName())) {
            queryWrapper.like("name", employee.getName());
        }
        if (employee.getStatus() != null) {
            queryWrapper.eq("status", employee.getStatus());
        }
        if (query.getStartDate() != null && query.getEndDate() != null) {
            queryWrapper.between("created_at", query.getStartDate(), query.getEndDate());
        }
        queryWrapper.eq("is_delete", 0);

        // 使用 PageHelper 进行分页查询
        Page<Employee> page = PageHelper.startPage(currentPage, pageSize);
        List<Employee> employees = employeeService.list(queryWrapper);

        // 为每个员工获取角色
        for (Employee emp : employees) {
            List<Role> roles = roleService.getRoleByEmployeeId(emp.getId());
            emp.setRoles(roles);
        }

        // 封装查询结果为 PageInfo 对象
        PageInfo<Employee> pageInfo = new PageInfo<>(employees);

        return pageInfo;
    }


    /**
     * 根据id删除员工信息 实则将status改为1
     *
     * @param id
     * @return
     */
    @RequestMapping("/deleteEmployee/{id}")
    public Object deleteEmployee(@PathVariable Long id) {
        // 从数据库中获取员工信息
        Employee employee = employeeService.getById(id);
        if (employee != null) {
            // 将员工的状态改为1，代表删除
            employee.setIsDelete(1);
            // 更新员工信息
            employeeService.updateById(employee);
        }
        // 返回相应的结果
        return true;
    }

    /**
     * 根据员工id修改status值
     *
     * @param id
     * @return
     */
    @RequestMapping("/updateStatus/{id}")
    public Object updateEmployeeStatus(@PathVariable Long id) {
        // 根据员工ID从数据库中获取员工信息
        Employee employee = employeeService.getById(id);

        if (employee != null) {
            // 更新员工的状态
            // 切换状态，如果为0则 1-0=1 如果为 1 啧1-1=0
            employee.setStatus(1 - employee.getStatus());

            // 执行更新员工信息的操作
            employeeService.updateById(employee);
        }
        return true;
    }

    /**
     * 编辑员工
     *
     * @param employee
     * @return
     */
    @RequestMapping("/editEmployee")
    public Object editEmployee(@RequestBody Employee employee) {
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", employee.getId());
        // 执行更新操作
        employeeService.update(employee, queryWrapper);

        return true;
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @RequestMapping("/addEmployee")
    public Object addEmployee(@RequestBody Employee employee) {
        // 调用employeeService的add方法添加员工信息
        employeeService.save(employee);
        return true;
    }


    /**
     * 先根据用户id,删除先前所有的角色
     * 再次批量增加新的数据
     *
     * @param employeeRole 存储EmpId和Role列表的id
     * @return
     */
    @Transactional
    @RequestMapping("/updateEmployeeRoles")
    public Boolean updateRoles(@RequestBody EmployeeRole employeeRole) {

        // 根据员工ID删除先前所有的角色
        employeeRoleService.remove(new QueryWrapper<EmployeeRole>().eq("employee_id", employeeRole.getEmployeeId()));

        // 批量根据员工ID增加角色
        employeeRoleService.batchAddRoles(employeeRole.getEmployeeId(), employeeRole.getRoles());

        return true;
    }

}
